package com.exsun.ex1077.ui.activity.trackdetail

import android.os.Bundle
import android.text.TextPaint
import android.view.View
import android.widget.SeekBar
import androidx.lifecycle.viewModelScope
import com.amap.api.maps.AMap
import com.amap.api.maps.model.*
import com.amap.api.maps.utils.SpatialRelationUtil
import com.amap.api.maps.utils.overlay.MovingPointOverlay
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityTrackDetailBinding
import com.exsun.ex1077.network.entity.TrackDetail
import com.exsun.ex1077.network.entity.VehicleTrack
import com.zhangping.amap.AMapHelper
import com.zhangping.amap.extend.getBounds
import com.zhangping.amap.trace.SmartMovingPointOverlay
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.toView
import kotlinx.android.synthetic.main.activity_track_detail.*
import kotlinx.android.synthetic.main.map_track_marker_vehicleno.view.*
import kotlinx.coroutines.launch

/**
 * 描述：轨迹详情
 * 作者：ZhangPing
 * 创建时间：2022/5/17 8:58
 */
class TrackDetailActivity: BaseActivity<TrackDetailViewModel, ActivityTrackDetailBinding>() {

    override fun title() = "轨迹详情"
    private lateinit var aMapHelper: AMapHelper
    //轨迹经纬度集合
    private var latLngList: MutableList<LatLng>? = null
    //轨迹对象集合
    private var modelList: List<TrackDetail>? = null
    //车子图标
    private var smoothMarker: SmartMovingPointOverlay? = null
    private var smoothTotalTime: Int = 30
    //上次停止滑动时得索引
    private var lastSmoothIndex = 0

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        super.initView(savedInstanceState)
        mViewModel.apply {
            model.set(intent.getSerializableExtra("model") as VehicleTrack)
            vehicleNo = mViewModel.model.get()?.vehicleNo ?: ""
            objType = intent.getIntExtra("objType", 0)
        }
        //初始化地图
        aMapHelper = AMapHelper(mapView.map).apply {
            bindLifecycle(lifecycle, mapView)
            applyStyle()
            applyCustomStyle(R.raw.style, R.raw.style_extra)
            animateMap()
        }
        //设置车牌信息窗
        aMapHelper.map.setInfoWindowAdapter(object : AMap.InfoWindowAdapter{

            override fun getInfoWindow(marker: Marker): View{
                val view = R.layout.map_track_marker_vehicleno.toView()
                view.title.text = marker.title
                return view
            }

            override fun getInfoContents(marker: Marker): View? = null
        })
        aMapHelper.map.setOnInfoWindowClickListener {
            if (it.isInfoWindowShown) it.hideInfoWindow() else it.showInfoWindow()
        }
        aMapHelper.map.setOnMarkerClickListener {
            if (it.title != mViewModel.vehicleNo) return@setOnMarkerClickListener true
            if (it.isInfoWindowShown) it.hideInfoWindow() else it.showInfoWindow()
            return@setOnMarkerClickListener true
        }
        //播放按钮点击事件
        play.setOnCheckedChangeListener { button, checked ->
            if (latLngList.isNullOrEmpty()) return@setOnCheckedChangeListener
            if (checked){
                //开始播放
                addSmoothMarker(lastSmoothIndex)
                smoothMarker?.startSmoothMove()
            }else{
                //停止播放
                smoothMarker?.stopMove()
                lastSmoothIndex += smoothMarker?.index ?: 0 + 1
            }
        }
        //进度条拖动事件
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (!fromUser || modelList.isNullOrEmpty()) return
                val model = modelList!![progress]
                currentTime.text = model.gdt ?: ""
                currentSpeed.text = "${model.spd}km/h"
                currentAddress.text = "当前位置：" + model.ars
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                //用户开始拖拽
                play.isChecked = false
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                //用户结束拖拽
                if (modelList.isNullOrEmpty()) return
                lastSmoothIndex = seekBar.progress
                //如果拖动到最后了，则重新从头开始
                if (lastSmoothIndex >= modelList!!.size - 1) lastSmoothIndex = 0
                addSmoothMarker(lastSmoothIndex)
            }
        })
        //加载数据
        mViewModel.loadData()
    }

    private fun addSmoothMarker(startIndex: Int){
        //车牌信息窗偏移量计算
        val infoWindowWidth = TextPaint().run {
            textSize = sp2px(12).toFloat()
            val textWidth = measureText(mViewModel.vehicleNo)
            textWidth + dp2px(16 + 8)
        }
        val infoWindowXOffset = Math.max((infoWindowWidth / 2).toInt() + dp2px(5), dp2px(53))
        //添加车子图标
        val bitmap = when(mViewModel.objType){
            Constant.OBJECT_TYPE_VEHICLE -> {
                R.drawable.track_vehicle.toBitmap(13, 31)
            }
            Constant.OBJECT_TYPE_SHIP -> {
                R.drawable.track_ship.toBitmap(36, 35)
            }
            Constant.OBJECT_TYPE_PERSON -> {
                R.drawable.track_person.toBitmap(34, 34)
            }
            Constant.OBJECT_TYPE_ANIMAL -> {
                R.drawable.track_animal.toBitmap(34, 42)
            }
            Constant.OBJECT_TYPE_OBJECT -> {
                R.drawable.track_object.toBitmap(36, 37)
            }
            else -> R.drawable.track_other.toBitmap(34, 34)
        }
        val vehicleMarker = mapView.map.addMarker(MarkerOptions()
            .anchor(0.5F, 0.5F)
            .title(mViewModel.vehicleNo)
            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
            .setInfoWindowOffset(infoWindowXOffset, dp2px(38))
        ).apply {
            //显示车牌号
            showInfoWindow()
        }
        smoothMarker?.destroy()
        smoothMarker = SmartMovingPointOverlay(mapView.map, vehicleMarker)
        smoothMarker?.setEnableRotate(mViewModel.objType == Constant.OBJECT_TYPE_VEHICLE)
        //取轨迹第一个点作为车子起点
        val drivePoint = latLngList!![startIndex]
        val pair = SpatialRelationUtil.calShortestDistancePoint(latLngList, drivePoint)
        latLngList!![pair.first] = drivePoint
        val subList = latLngList!!.subList(pair.first, latLngList!!.size)
        //设置轨迹点
        smoothMarker?.setPoints(subList)
        //设置平滑移动的总时间,单位秒
        val duration = smoothTotalTime - (startIndex / modelList!!.size.toFloat() * smoothTotalTime).toInt()
        smoothMarker?.setTotalDuration(duration)
//        smoothMarker?.setMoveListener(smoothMoveListener)
        smoothMarker?.setMoveListener{
            val index = startIndex + smoothMarker!!.index
            val model = modelList!![index]
            //如果播放完成则恢复播放按钮
            if (index + 2 >= latLngList!!.size){
                play.isChecked = false
                lastSmoothIndex = 0
            }else {
                lastSmoothIndex = index
            }
            runOnUiThread {
                //设置进度条
                seekBar.progress = index
                //当前时间
                currentTime.text = "${model.gdt}"
                //当前速度
                currentSpeed.text = "${model.spd}km/h"
                //设置地址
                currentAddress.text = "当前位置：" + model.ars
            }
        }


    }

//    private val smoothMoveListener = SmartMovingPointOverlay.MoveListener {
//        val index = smoothMarker!!.index + lastSmoothIndex + 1
//        val model = modelList!![index]
//        mViewModel.viewModelScope.launch {
//            model.logJson("当前数据：")
//            //设置进度条
//            seekBar.progress = index
//            //当前时间
//            currentTime.text = "${model.gdt}"
//            //当前速度
//            currentSpeed.text = "${model.spd}km/h"
//            //设置地址
//            currentAddress.text = "当前位置：" + model.ars
//            //如果播放完成则恢复播放按钮
//            if (index + 1 >= modelList!!.size){
//                play.isChecked = false
//                lastSmoothIndex = 0
//            }
//        }
//    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.trackDetailResult.observe(this){
            parseState(it, {
                if (it.isNullOrEmpty()) return@parseState
                //更新UI
                val first = it.first()
                val last = it.last()
                currentTime.text = "${first.gdt}"
                currentSpeed.text = "${first.spd}km/h"
                currentAddress.text = "当前位置：" + first.ars
                seekBar.max = it.size - 1
                seekBarStartTime.text = first.gdt?.split(" ")?.get(1) ?: ""
                seekBarEndTime.text = last.gdt?.split(" ")?.get(1) ?: ""
                //绘制地图
                updateMapUI(it)
            })
        }
    }

    private fun updateMapUI(gpsList: List<TrackDetail>){
        modelList = gpsList
        latLngList = gpsList.map { it.getLatLng() }.toMutableList()
        val first = latLngList!!.first()
        val last = latLngList!!.last()
        //添加起点Marker
        mapView.map.addMarker(MarkerOptions()
            .position(first)
            .anchor(0.5F, 0.5F)
            .zIndex(0F)
            .infoWindowEnable(false)
            .icon(BitmapDescriptorFactory.fromBitmap(R.drawable.map_track_start_marker.toBitmap(46, 57)))
        )
        //添加终点Marker
        mapView.map.addMarker(MarkerOptions()
            .position(last)
            .anchor(0.5F, 0.5F)
            .zIndex(1F)
            .infoWindowEnable(false)
            .icon(BitmapDescriptorFactory.fromBitmap(R.drawable.map_track_end_marker.toBitmap(46, 57)))
        )
        //添加轨迹
        mapView.map.addPolyline(PolylineOptions()
            .addAll(latLngList)
            .width(dp2px(5).toFloat())
            .setDottedLine(true)
            .color(R.color.color_F18E56.toColorRes())
        )
        aMapHelper.animateMap(getBounds(latLngList!!), 200)
    }

    override fun onDestroy() {
        super.onDestroy()
        smoothMarker?.destroy()
    }

}